<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <a-tabs defaultActiveKey="1">
        <a-tab-pane key="1" tab="基本信息">
          <a-form :form="form">
            <a-form-item label="半料编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入半料编号" v-decorator="['materialCode', validatorRules.materialCode]" :disabled="disableEdit" />
            </a-form-item>
            <a-form-item label="半料名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入半料名称" v-decorator="['materialName', validatorRules.materialName]" />
            </a-form-item>
            <a-form-item label="物料图片" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-image-upload v-decorator="['materialImage']" :number="1" :bizPath="bizPath" :returnUrl="true" @change="handleImageChange" @error="handleImageError"></j-image-upload>
            </a-form-item>
            <a-form-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入单位" v-decorator="['unit', validatorRules.unit]" />
            </a-form-item>
            <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea placeholder="请输入备注" v-decorator="['remark']" :rows="4" />
            </a-form-item>
            <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="radio" v-decorator="['status', {initialValue: '0'}]" :triggerChange="true" dictCode="wms_material_status" />
            </a-form-item>
          </a-form>
        </a-tab-pane>
        <a-tab-pane key="2" tab="组成明细" forceRender>
          <a-tabs defaultActiveKey="profile1" @change="handleTabChange">
            <a-tab-pane key="profile1" tab="型材">
              <div class="table-operator">
                <a-button type="primary" icon="plus" style="margin-bottom: 16px;" @click="handleAddMaterialModal('1')">添加型材</a-button>
                <a-button type="danger" icon="delete" style="margin-left: 8px; margin-bottom: 16px;" @click="handleClearTypeDetails('1')" :disabled="getDetailsByType('1').length === 0">清空型材</a-button>
              </div>
              
              <a-table
                size="middle"
                bordered
                rowKey="id"
                :columns="profileColumns"
                :dataSource="getDetailsByType('1')"
                :pagination="false"
                :scroll="{ y: 200, x: 'max-content' }">
                
                <template slot="materialNameSlot" slot-scope="text">
                  {{ text }}
                </template>
                
                <template slot="quantitySlot" slot-scope="text, record">
                  <a-input-number
                    v-model="record.quantity"
                    :min="0.01"
                    :step="0.01"
                    :precision="2"
                    style="width: 100%"
                    placeholder="请输入数量"
                    @change="handleQuantityChange"
                  />
                </template>
                
                <template slot="actionSlot" slot-scope="text, record">
                  <a-button type="danger" icon="delete" size="small" @click="removeDetail(record.id)">删除</a-button>
                </template>
              </a-table>
            </a-tab-pane>
            
            <a-tab-pane key="profile2" tab="配件" forceRender>
              <div class="table-operator">
                <a-button type="primary" icon="plus" style="margin-bottom: 16px;" @click="handleAddMaterialModal('2')">添加配件</a-button>
                <a-button type="danger" icon="delete" style="margin-left: 8px; margin-bottom: 16px;" @click="handleClearTypeDetails('2')" :disabled="getDetailsByType('2').length === 0">清空配件</a-button>
              </div>
              
              <a-table
                size="middle"
                bordered
                rowKey="id"
                :columns="fittingColumns"
                :dataSource="getDetailsByType('2')"
                :pagination="false"
                :scroll="{ y: 200, x: 'max-content' }">
                
                <template slot="materialNameSlot" slot-scope="text">
                  {{ text }}
                </template>
                
                <template slot="quantitySlot" slot-scope="text, record">
                  <a-input-number
                    v-model="record.quantity"
                    :min="0.01"
                    :step="0.01"
                    :precision="2"
                    style="width: 100%"
                    placeholder="请输入数量"
                    @change="handleQuantityChange"
                  />
                </template>
                
                <template slot="actionSlot" slot-scope="text, record">
                  <a-button type="danger" icon="delete" size="small" @click="removeDetail(record.id)">删除</a-button>
                </template>
              </a-table>
            </a-tab-pane>
            
            <a-tab-pane key="profile3" tab="辅件" forceRender>
              <div class="table-operator">
                <a-button type="primary" icon="plus" style="margin-bottom: 16px;" @click="handleAddMaterialModal('3')">添加辅件</a-button>
                <a-button type="danger" icon="delete" style="margin-left: 8px; margin-bottom: 16px;" @click="handleClearTypeDetails('3')" :disabled="getDetailsByType('3').length === 0">清空辅件</a-button>
              </div>
              
              <a-table
                size="middle"
                bordered
                rowKey="id"
                :columns="auxiliaryColumns"
                :dataSource="getDetailsByType('3')"
                :pagination="false"
                :scroll="{ y: 200, x: 'max-content' }">
                
                <template slot="materialNameSlot" slot-scope="text">
                  {{ text }}
                </template>
                
                <template slot="quantitySlot" slot-scope="text, record">
                  <a-input-number
                    v-model="record.quantity"
                    :min="0.01"
                    :step="0.01"
                    :precision="2"
                    style="width: 100%"
                    placeholder="请输入数量"
                    @change="handleQuantityChange"
                  />
                </template>
                
                <template slot="actionSlot" slot-scope="text, record">
                  <a-button type="danger" icon="delete" size="small" @click="removeDetail(record.id)">删除</a-button>
                </template>
              </a-table>
            </a-tab-pane>
          </a-tabs>
        </a-tab-pane>
      </a-tabs>
    </a-spin>
    
    <!-- 物料选择模态框 -->
    <a-modal
      :title="materialModalTitle"
      :visible="materialModalVisible"
      :width="1000"
      @ok="handleMaterialSelectOk"
      @cancel="handleMaterialSelectCancel">
      <a-spin :spinning="materialSelectLoading">
        <!-- 搜索表单 -->
        <a-form layout="inline" class="material-select-form">
          <a-form-item label="物料编号">
            <a-input placeholder="请输入物料编号" v-model="materialQueryParam.materialCode" />
          </a-form-item>
          <a-form-item label="物料名称">
            <a-input placeholder="请输入物料名称" v-model="materialQueryParam.materialName" />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="searchMaterial">查询</a-button>
            <a-button style="margin-left: 8px" @click="resetMaterialQuery">重置</a-button>
          </a-form-item>
        </a-form>
        
        <!-- 物料表格 -->
        <a-table
          ref="materialTable"
          size="middle"
          bordered
          rowKey="id"
          :columns="materialColumns"
          :dataSource="materialDataSource"
          :pagination="materialPagination"
          :loading="materialSelectLoading"
          :rowSelection="{selectedRowKeys: selectedMaterialIds, onChange: onMaterialSelectionChange}"
          @change="handleMaterialTableChange">
        </a-table>
      </a-spin>
    </a-modal>
  </j-modal>
</template>

<script>
  import { materialAdd, materialEdit } from '@/api/wms'
  import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
  import JDictLabel from '@/components/dict/JDictLabel.vue'
  import { getAction, postAction, downFile } from '@/api/manage'
  import JModal from '@/components/jeecg/JModal/JModal'
  import JImageUpload from '@/components/jeecg/JImageUpload'
  import pick from 'lodash.pick'
  import * as XLSX from 'xlsx'

  export default {
    name: 'SemiModal',
    components: {
      JDictSelectTag,
      JDictLabel,
      JModal,
      JImageUpload
    },
    data() {
      return {
        form: this.$form.createForm(this),
        title: '操作',
        width: 900,
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        confirmLoading: false,
        validatorRules: {
          materialCode: { rules: [{ required: true, message: '请输入半料编号!' }] },
          materialName: { rules: [{ required: true, message: '请输入半料名称!' }] },
          unit: { rules: [{ required: true, message: '请输入单位!' }] },
        },
        bizPath: 'material/semi',
        disableEdit: false,
        // 组成明细
        detailList: [],
        // 型材表格列
        profileColumns: [
          {
            title: '物料编号',
            align: 'center',
            dataIndex: 'materialCode',
            width: 120
          },
          {
            title: '型材名称',
            align: 'center',
            dataIndex: 'materialName',
            width: 150
          },
          {
            title: '颜色',
            align: 'center',
            dataIndex: 'color',
            width: 80
          },
          {
            title: '宽度(mm)',
            align: 'center',
            dataIndex: 'width',
            width: 100
          },
          {
            title: '高度(mm)',
            align: 'center',
            dataIndex: 'height',
            width: 100
          },
          {
            title: '数量',
            align: 'center',
            dataIndex: 'quantity',
            width: 100,
            scopedSlots: { customRender: 'quantitySlot' }
          },
          {
            title: '单位',
            align: 'center',
            dataIndex: 'unit',
            width: 80
          },
          {
            title: '单位成本',
            align: 'center',
            dataIndex: 'unitCost',
            width: 100,
            customRender: (text) => {
              return text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00';
            }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            width: 80,
            scopedSlots: { customRender: 'actionSlot' }
          }
        ],
        // 配件表格列
        fittingColumns: [
          {
            title: '物料编号',
            align: 'center',
            dataIndex: 'materialCode',
            width: 120
          },
          {
            title: '配件名称',
            align: 'center',
            dataIndex: 'materialName',
            width: 150
          },
          {
            title: '规格',
            align: 'center',
            dataIndex: 'specification',
            width: 120
          },
          {
            title: '颜色',
            align: 'center',
            dataIndex: 'color',
            width: 80
          },
          {
            title: '品牌',
            align: 'center',
            dataIndex: 'brand',
            width: 100
          },
          {
            title: '数量',
            align: 'center',
            dataIndex: 'quantity',
            width: 100,
            scopedSlots: { customRender: 'quantitySlot' }
          },
          {
            title: '单位',
            align: 'center',
            dataIndex: 'unit',
            width: 80
          },
          {
            title: '单位成本',
            align: 'center',
            dataIndex: 'unitCost',
            width: 100,
            customRender: (text) => {
              return text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00';
            }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            width: 80,
            scopedSlots: { customRender: 'actionSlot' }
          }
        ],
        // 辅件表格列
        auxiliaryColumns: [
          {
            title: '物料编号',
            align: 'center',
            dataIndex: 'materialCode',
            width: 120
          },
          {
            title: '辅件名称',
            align: 'center',
            dataIndex: 'materialName',
            width: 150
          },
          {
            title: '规格',
            align: 'center',
            dataIndex: 'specification',
            width: 120
          },
          {
            title: '颜色',
            align: 'center',
            dataIndex: 'color',
            width: 80
          },
          {
            title: '品牌',
            align: 'center',
            dataIndex: 'brand',
            width: 100
          },
          {
            title: '数量',
            align: 'center',
            dataIndex: 'quantity',
            width: 100,
            scopedSlots: { customRender: 'quantitySlot' }
          },
          {
            title: '单位',
            align: 'center',
            dataIndex: 'unit',
            width: 80
          },
          {
            title: '单位成本',
            align: 'center',
            dataIndex: 'unitCost',
            width: 100,
            customRender: (text) => {
              return text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00';
            }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            width: 80,
            scopedSlots: { customRender: 'actionSlot' }
          }
        ],
        // 当前物料类型
        currentMaterialType: '',
        materialTypeDict: {}, // 用于存储物料类型字典
        
        // 物料选择模态框相关属性
        materialModalVisible: false,
        materialModalTitle: '选择物料',
        materialSelectLoading: false,
        materialQueryParam: {
          materialCode: '',
          materialName: '',
          materialType: ''
        },
        materialDataSource: [],
        selectedMaterialIds: [],
        selectedMaterials: [],
        materialColumns: [
          {
            title: '物料编号',
            align: 'center',
            dataIndex: 'materialCode',
            width: 120
          },
          {
            title: '物料名称',
            align: 'center',
            dataIndex: 'materialName',
            width: 150
          },
          {
            title: '规格',
            align: 'center',
            dataIndex: 'specification',
            width: 120
          },
          {
            title: '颜色',
            align: 'center',
            dataIndex: 'color',
            width: 80
          },
          {
            title: '单位',
            align: 'center',
            dataIndex: 'unit',
            width: 80
          },
          {
            title: '单位成本',
            align: 'center',
            dataIndex: 'unitCost',
            width: 100,
            customRender: (text) => {
              return text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00';
            }
          }
        ],
        materialPagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showTotal: total => `共 ${total} 条`,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '30', '50', '100']
        }
      }
    },
    created() {
      // 加载物料类型字典
      this.loadMaterialTypeDict()
    },
    methods: {
      // 加载物料类型字典
      loadMaterialTypeDict() {
        getAction('/sys/dict/getDictItems/material_type').then(res => {
          if (res.success) {
            const dict = {}
            res.result.forEach(item => {
              dict[item.itemText] = item.itemValue
            })
            this.materialTypeDict = dict
          }
        })
      },
      add() {
        this.edit({
          materialType: '6', // 半料类型
          status: '0' // 默认启用状态
        })
      },
      edit(record) {
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.visible = true
        this.disableEdit = !!this.model.id
        this.detailList = []
        
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'materialCode', 'materialName', 'materialType', 'specification', 'unit', 'materialImage', 'remark', 'status'))
          
          // 如果是编辑模式，加载组成明细
          if (this.model.id) {
            this.loadMaterialDetails()
          }
        })
      },
      loadMaterialDetails() {
        getAction('/wms/material/detail/list', { materialId: this.model.id }).then(res => {
          if (res.success) {
            this.detailList = res.result || []
          }
        })
      },
      close() {
        this.$emit('close')
        this.visible = false
      },
      handleOk() {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            
            // 处理图片路径
            if (values.materialImage && values.materialCode) {
              // 确保materialImage是字符串
              if (typeof values.materialImage !== 'string') {
                console.warn('物料图片不是字符串类型:', values.materialImage);
                if (values.materialImage && typeof values.materialImage === 'object') {
                  if (values.materialImage.response && values.materialImage.response.message) {
                    values.materialImage = values.materialImage.response.message;
                  } else {
                    values.materialImage = JSON.stringify(values.materialImage);
                  }
                } else {
                  values.materialImage = '';
                }
              }
              
              // 重命名图片，格式：租户ID_物料编码
              const tenantId = this.$store.getters.userInfo.tenantId || '';
              values.materialImage = values.materialImage.replace(/\/material\/semi\//, `/material/semi/${tenantId}_${values.materialCode}_`);
            }
            
            let formData = Object.assign(this.model, values)
            
            // 计算半料单位成本
            const unitCost = this.calculateTotalCost()
            formData.unitCost = unitCost
            
            let obj = {
              ...formData,
              detailList: this.detailList // 直接将组成明细列表传给后端
            }
            
            // 验证明细
            if (this.detailList.length === 0) {
              this.$message.warning('请至少添加一条组成明细!')
              that.confirmLoading = false
              return
            }
            
            // 验证明细数据
            for (let i = 0; i < this.detailList.length; i++) {
              const detail = this.detailList[i]
              if (!detail.materialType) {
                this.$message.warning(`第${i+1}行物料类型不能为空!`)
                that.confirmLoading = false
                return
              }
              if (!detail.materialCode) {
                this.$message.warning(`第${i+1}行物料不能为空!`)
                that.confirmLoading = false
                return
              }
              if (!detail.quantity || detail.quantity <= 0) {
                this.$message.warning(`第${i+1}行数量必须大于0!`)
                that.confirmLoading = false
                return
              }
            }
            
            if (!this.model.id) {
              // 新增
              materialAdd(obj).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                  that.confirmLoading = false
                }
              }).finally(() => {
                that.confirmLoading = false
                that.close()
              })
            } else {
              // 编辑
              materialEdit(obj).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                  that.confirmLoading = false
                }
              }).finally(() => {
                that.confirmLoading = false
                that.close()
              })
            }
          }
        })
      },
      handleCancel() {
        this.close()
      },
      handleImageChange(value) {
        console.log('物料图片变更:', value);
        
        // 处理不同类型的输入
        let imagePath = '';
        
        if (typeof value === 'string') {
          // 如果是字符串，直接使用
          imagePath = value;
        } else if (value && typeof value === 'object') {
          // 如果是对象，尝试提取路径
          if (value.response && value.response.message) {
            imagePath = value.response.message;
          } else if (Array.isArray(value)) {
            // 如果是数组，提取每个元素的路径并拼接
            imagePath = value.map(item => {
              if (typeof item === 'string') return item;
              if (item && item.response && item.response.message) return item.response.message;
              return '';
            }).filter(Boolean).join(',');
          } else {
            console.warn('物料图片格式不正确:', JSON.stringify(value));
          }
        }
        
        console.log('处理后的物料图片路径:', imagePath);
        
        // 设置表单值
        this.form.setFieldsValue({
          materialImage: imagePath
        });
      },
      // 处理图片加载错误
      handleImageError(e) {
        console.error('图片加载失败:', e);
        e.target.style.display = 'none';
        const container = e.target.parentNode;
        if (container) {
          const icon = document.createElement('i');
          icon.className = 'anticon anticon-picture';
          icon.style.fontSize = '24px';
          icon.style.color = '#d9d9d9';
          container.insertBefore(icon, e.target);

          const errorText = document.createElement('div');
          errorText.innerText = '图片不存在';
          errorText.style.color = '#ff4d4f';
          errorText.style.fontSize = '12px';
          errorText.style.marginTop = '4px';
          container.appendChild(errorText);
        }
      },
      // 处理标签页切换
      handleTabChange(activeKey) {
        console.log('Tab changed:', activeKey);
      },
      // 根据类型获取明细
      getDetailsByType(type) {
        return this.detailList.filter(item => item.materialType === type);
      },
      // 打开物料选择对话框
      handleAddMaterialModal(materialType) {
        this.currentMaterialType = materialType;
        this.materialQueryParam.materialType = materialType;
        this.materialModalTitle = `选择${this.getMaterialTypeTitle(materialType)}`;
        this.materialModalVisible = true;
        this.selectedMaterialIds = [];
        this.selectedMaterials = [];
        this.searchMaterial();
      },
      // 获取物料类型标题
      getMaterialTypeTitle(type) {
        switch (type) {
          case '1': return '型材';
          case '2': return '配件';
          case '3': return '辅件';
          default: return '物料';
        }
      },
      // 搜索物料
      searchMaterial() {
        this.materialSelectLoading = true;
        this.materialPagination.current = 1;
        this.loadMaterialData();
      },
      // 重置物料查询
      resetMaterialQuery() {
        this.materialQueryParam = {
          materialCode: '',
          materialName: '',
          materialType: this.currentMaterialType
        };
        this.searchMaterial();
      },
      // 加载物料数据
      loadMaterialData() {
        const params = {
          pageNo: this.materialPagination.current,
          pageSize: this.materialPagination.pageSize,
          materialType: this.materialQueryParam.materialType,
          materialCode: this.materialQueryParam.materialCode,
          materialName: this.materialQueryParam.materialName
        };
        
        getAction('/wms/material/list', params).then(res => {
          if (res.success) {
            this.materialDataSource = res.result.records || [];
            this.materialPagination.total = res.result.total || 0;
          } else {
            this.$message.warning(res.message);
          }
          this.materialSelectLoading = false;
        }).catch(() => {
          this.materialSelectLoading = false;
        });
      },
      // 处理物料表格变化
      handleMaterialTableChange(pagination) {
        this.materialPagination.current = pagination.current;
        this.materialPagination.pageSize = pagination.pageSize;
        this.loadMaterialData();
      },
      // 物料选择变化
      onMaterialSelectionChange(selectedRowKeys, selectedRows) {
        this.selectedMaterialIds = selectedRowKeys;
        this.selectedMaterials = selectedRows;
      },
      // 处理物料选择确认
      handleMaterialSelectOk() {
        if (this.selectedMaterials.length === 0) {
          this.$message.warning(`请选择${this.getMaterialTypeTitle(this.currentMaterialType)}`);
          return;
        }
        
        // 添加选中的物料到明细列表
        const promises = this.selectedMaterials.map(material => {
          return this.getMaterialDetail(material.materialCode).then(detailMaterial => {
            // 检查是否已存在
            const existingIndex = this.detailList.findIndex(item => 
              item.materialCode === material.materialCode && 
              item.materialType === this.currentMaterialType
            );
            
            if (existingIndex === -1) {
              // 不存在，添加新记录
              const newDetail = {
                id: this.generateTempId(),
                materialType: this.currentMaterialType,
                materialCode: material.materialCode,
                materialName: material.materialName,
                specification: material.specification || '',
                quantity: 1,
                unit: material.unit || '',
                unitCost: detailMaterial ? (detailMaterial.unitCost || 0) : (material.unitCost || 0), // 优先使用详情中的单位成本
                remark: ''
              };
              
              // 根据物料类型添加特定字段
              if (this.currentMaterialType === '1') { // 型材
                newDetail.color = material.color || '';
                newDetail.length = material.length || '';
                newDetail.width = material.width || '';
                newDetail.height = material.height || '';
                newDetail.weight = material.weight || '';
              } else if (this.currentMaterialType === '2' || this.currentMaterialType === '3') { // 配件或辅件
                newDetail.color = material.color || '';
                newDetail.brand = material.brand || '';
              }
              
              this.detailList.push(newDetail);
            }
          });
        });
        
        // 等待所有请求完成
        Promise.all(promises).then(() => {
          this.$message.success(`成功添加${this.selectedMaterials.length}个${this.getMaterialTypeTitle(this.currentMaterialType)}`);
          this.materialModalVisible = false;
        }).catch(error => {
          console.error('获取物料详情失败:', error);
          this.$message.error('获取物料详情失败，请重试');
        });
      },
      // 取消物料选择
      handleMaterialSelectCancel() {
        this.materialModalVisible = false;
      },
      // 移除明细
      removeDetail(id) {
        const index = this.detailList.findIndex(item => item.id === id);
        if (index !== -1) {
          this.detailList.splice(index, 1);
        }
      },
      // 清空指定类型的明细
      handleClearTypeDetails(type) {
        this.$confirm({
          title: '确认清空',
          content: `确定要清空所有${this.getMaterialTypeTitle(type)}明细吗？`,
          okText: '确认',
          cancelText: '取消',
          onOk: () => {
            this.detailList = this.detailList.filter(item => item.materialType !== type);
          }
        });
      },
      // 生成临时ID
      generateTempId() {
        return 'temp_' + new Date().getTime() + '_' + Math.floor(Math.random() * 1000);
      },
      
      // 获取物料详情
      getMaterialDetail(materialCode) {
        return new Promise((resolve, reject) => {
          if (!materialCode) {
            resolve(null);
            return;
          }
          
          getAction('/wms/material/queryByCode', { materialCode: materialCode }).then(res => {
            if (res.success) {
              resolve(res.result);
            } else {
              resolve(null);
            }
          }).catch(error => {
            console.error('获取物料详情失败:', error);
            resolve(null);
          });
        });
      },
      
      // 处理数量变化
      handleQuantityChange() {
        // 数量变化时，重新计算总成本
        this.calculateTotalCost();
      },
      
      // 计算半料总成本
      calculateTotalCost() {
        let totalCost = 0;
        
        // 遍历所有明细，计算总成本
        this.detailList.forEach(detail => {
          // 查询物料的单位成本
          const materialCost = detail.unitCost || 0;
          const quantity = detail.quantity || 0;
          
          // 累加成本
          totalCost += materialCost * quantity;
        });
        
        // 返回计算结果，保留两位小数
        return parseFloat(totalCost.toFixed(2));
      }
    }
  }
</script>

<style scoped>
  .ant-form-item {
    margin-bottom: 8px;
  }
  
  .table-operator {
    margin-bottom: 16px;
  }
  
  .table-operator button {
    margin-right: 8px;
  }
  
  .material-select-form {
    margin-bottom: 16px;
  }
</style>

<style>
  /* 修复表格头部固定问题 */
  .ant-table-header {
    overflow: hidden !important;
    margin-bottom: 0 !important;
    padding-bottom: 0 !important;
  }
  
  .ant-table-body {
    overflow-y: auto !important;
  }
  
  /* 隐藏表格下方的选择区域 */
  .ant-table-footer {
    display: none !important;
  }
  
  .ant-table-placeholder {
    border-bottom: 1px solid #e8e8e8;
  }
</style> 